package com.dmall.chapter06.section05;

public class LeetCode200 {

    private int R, C;
    private boolean[][] visited;
    private char[][] grid;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int numIslands(char[][] grid) {
        if (grid == null) {
            return 0;
        }

        R = grid.length;
        if (R == 0) {
            return 0;
        }

        C = grid[0].length;
        if (C == 0) {
            return 0;
        }
        visited = new boolean[R][C];

        this.grid = grid;

        int res = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (!visited[i][j] && grid[i][j] == '1') {
                    dfs(i, j);
                    res ++;
                }
            }
        }

        return res;
    }

    private void dfs(int x, int y) {
        visited[x][y] = true;
        if (grid[x][y] == '1') {
            for (int i = 0; i < dirs.length; i++) {
                int nextx = x + dirs[i][0];
                int nexty = y + dirs[i][1];
                if (inArea(nextx, nexty) && !visited[nextx][nexty] && grid[nextx][nexty] == '1') {
                    dfs(nextx, nexty);
                }
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        char[][] grid = {
            {'1', '1', '0', '0', '0'},
            {'1', '1', '0', '0', '0'},
            {'0', '0', '1', '0', '0'},
            {'0', '0', '0', '1', '1'}
        };
        LeetCode200 leetCode200 = new LeetCode200();
        int nums = leetCode200.numIslands(grid);
        System.out.println(nums);
    }
}
